import React, { useState, useEffect, useRef } from 'react'
import { Modal, Space } from 'antd';
import { ProTable } from '@ant-design/pro-components';
import { useNavigate } from 'react-router-dom';
import TheButton from "@/components/TheButton/index.jsx";
import { apiSeckillActivityPage, apiSeckillActivityFinish } from "@/api/marketingTool/kill.js";
import {useWindowSize} from "@/utils/useWindowSize.js";

const { confirm } = Modal;
export default () => {
  const {width, height} = useWindowSize();
  const [tbScrollH, setTbScrollH] = useState('40vh');
  const [loadings, setLoadings] = useState([]);
  const navigate = useNavigate();
  const actionRef = useRef()
  const [closeLoading, setCloseLoading] = useState(false)
  const columns = [
    {
      title: "秒杀活动",
      dataIndex: "key",
      key: "key",
      hideInTable: true,
      fieldProps: {
        placeholder: "请输入活动id/名称"
      }
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      hideInTable: true,
      valueType: 'select',
      initialValue: [''],
      fieldProps: {
        options: [
          {
            label: '全部',
            value: '',
          },
          {
            label: '未开始',
            value: '未开始',
          },
          {
            label: '进行中',
            value: '进行中',
          },
          {
            label: '已结束',
            value: '已结束',
          }
        ],
      },
    },
    {
      title: "活动ID",
      dataIndex: "activityId",
      key: "activityId",
      hideInSearch: true,
    },
    {
      title: "活动名称",
      dataIndex: "activityName",
      key: "activityName",
      hideInSearch: true,
    },
    {
      title: "活动类型",
      dataIndex: "activityType",
      key: "activityType",
      hideInSearch: true,
      render(text, record) {
        let txt = ''
        switch (record.activityType) {
          case 'SECKILL_HOMEPAGE':
            txt = '首页秒杀'
            break;
          case 'SECKILL_ACTIVITY':
            txt = '活动秒杀'
            break;
          default:
            break;
        }
        return txt
      }
    },
    {
      title: "活动时间",
      dataIndex: "warmingTime",
      key: "warmingTime",
      hideInSearch: true,
      render: (text, record) => {
        return record.warmingTime + '-' + record.realityEndTime
      }
    },
    {
      title: "秒杀开始",
      hideInSearch: true,
      dataIndex: "startTime",
      key: "startTime",
    },
    {
      title: "状态",
      dataIndex: "activityStatus",
      key: "activityStatus",
      hideInSearch: true,
    },
    {
      title: "最近修改时间",
      dataIndex: "updateTime",
      key: "updateTime",
      hideInSearch: true,
    },
    {
      title: "操作",
      dataIndex: "serviceShowFile",
      key: "serviceShowFile",
      hideInSearch: true,
      fixed:'right',
      width:200,
      render: (text, render, index) => {
        return (
          <Space>
            <TheButton haspermi={['marketingTool:kill:view']} type="link" onClick={() => onView(render)}>查看</TheButton>
            {
              render.activityStatus === '已结束' ? null :
                <>
                  <TheButton haspermi={['marketingTool:kill:edit']} type="link"
                    onClick={() => onEdit(render)}>修改</TheButton>
                  <TheButton haspermi={['marketingTool:kill:end']} type="link" loading={loadings[index]}
                    onClick={() => onClose(render,index)}>提前结束</TheButton>
                </>
            }
          </Space>
        )
      }
    },
  ]
  /**
   * @desc 关闭
   * */
  const onClose = async (render,RowIndex) => {
    setLoadings((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[RowIndex] = true;
      return newLoadings;
    });
    Modal.confirm({
      title: "提示",
      type: 'warning',
      content: "提前关闭秒杀活动可能导致正在购买的消费者无法正常下单，是否继续关闭？",
      onOk: async () => {
        await apiSeckillActivityFinish({ activityId: render.activityId }).then(res => {
          if (res.code === 0) {
            actionRef.current.reloadAndRest()
          }
        })
        setLoadings((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[RowIndex] = false;
          return newLoadings;
        });
      },
      onCancel: () => {
        setLoadings((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[RowIndex] = false;
          return newLoadings;
        });
      }
    });
  }
  /**
   * @desc 新建
   * */
  const onAdd = () => {
    navigate('/marketingTool/kill/event', {
      state: {
        mode: "add"
      }
    })
    // this.props.history.push(`/marketingTool/killAdd/null/add/null`)
  }
  /**
   * @desc 查看
   * */
  const onView = (render) => {
    navigate('/marketingTool/kill/event', {
      state: {
        mode: "view",
        activityId: render.activityId,
        activityType: render.activityType
      }
    })
    // this.props.history.push(`/marketingTool/killAdd/${render.activityId}/view/${render.activityType}`)
  }
  /**
   * @desc 编辑
   * */
  const onEdit = (render) => {
    navigate('/marketingTool/kill/event', {
      state: {
        mode: "edit",
        activityId: render.activityId,
        activityType: render.activityType
      }
    })
    // this.props.history.push(`/marketingTool/killAdd/${render.activityId}/edit/${render.activityType}`)
  }
  useEffect(() => {
    if (height >= 1080){
      setTbScrollH('58vh')
    }else if(height < 1080 && height >= 960){
      setTbScrollH('53vh')
    }
  }, [])
  return <div >
    <ProTable
      actionRef={actionRef}
      scroll={{ x: "max-content", y: tbScrollH }}
      rowKey={(record) => record.activityId}
      bordered={true}
      options={false}
      columns={columns}
      headerTitle={
        <TheButton haspermi={['marketingTool:kill:add']} key="add" onClick={() => onAdd()}>新建</TheButton>
      }
      pagination={{
        defaultPageSize: 10,
        position: ['bottomCenter'],
        showSizeChanger: false
      }}
      request={async (params, sort, filter) => {
        // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        // 如果需要转化参数可以在这里进行修改
        const res = await apiSeckillActivityPage({
          pageNo: params.current,
          pageSize: params.pageSize,
          ...params
        });
        return {
          data: res.rows,
          // success 请返回 true，
          // 不然 table 会停止解析数据，即使有数据
          success: res.code === 0,
          // 不传会使用 data 的长度，如果是分页一定要传
          total: res.totalCount,
        };
      }}
      search={{
        optionRender: (searchConfig, formProps, dom) => {
          return dom.reverse()
        }
      }}
    />
  </div>
}
